package com.zmj.commoncore.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import javafx.beans.binding.ObjectExpression;

/**
 * Created by: meijun
 * Date: 2017/12/22 20:31
 */
public class JsonUtil {

    /**
     * Gson
     * @param object
     * @return
     */
    public  static  String  toJson (Object object) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setPrettyPrinting();
        Gson gson = gsonBuilder.create();
        return  gson.toJson(object);
    }

    /**
     * fastjson
     * @param o
     * @return
     */
    public static JSONObject toJSONObject(Object o) {
        Object o1 = JSONObject.toJSON(o);
        return JSONObject.parseObject(o1.toString());
    }

    /**
     * fastjson
     * @param o
     * @return
     */
    public static <T> T toJavaBean(Object o,Class<T> t) {
        String s = JSONObject.toJSONString(JSONObject.toJSON(o));
        JSONObject parseObject = JSONObject.parseObject(s);
        return JSONObject.toJavaObject(parseObject, t);
    }

    /**
     *
     * @param str
     * @param t
     * @return
     */
    public static String toListString(String str,Class t) {
        return JSONArray.parseArray(str, t).toString();
    }

    /**
     * 实体类转json去掉值null的字段
     * @param o
     * @return
     */
    public static Object beanToObjectClearNullValue(Object o) {
        String s = JSONObject.toJSONString(o);
        Object parse = JSON.parse(s);
        return JSONObject.toJSON(parse);
    }

    /**
     * 实体类转json不去掉null的字段
     * @param o
     * @return
     */
    public static Object beanToObjectWriteMapNullValue(Object o) {
        //空的字段也输出
        String s = JSONObject.toJSONString(o, SerializerFeature.WriteMapNullValue);
        Object parse = JSON.parse(s);
        return JSONObject.toJSON(parse);
    }

    /**
     * 数值字段如果为null,输出为0,而非null
     * @param o
     * @return
     */
    public static Object beanToObjectWriteNullNumberAsZero(Object o) {
        //空的字段也输出
        String s = JSONObject.toJSONString(o, SerializerFeature.WriteNullNumberAsZero);
        Object parse = JSON.parse(s);
        return JSONObject.toJSON(parse);
    }

}
